package com.qf.aop.impl;

import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import com.qf.aop.annocation.OrderDataSource;
import com.qf.common.ShopException;
import com.qf.consants.RabbitMQConstants;
import com.qf.datasoruce.OrderTableIndexThreadLocal;
import com.qf.entity.User;
import com.qf.utils.OrderUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.omg.CORBA.INTERNAL;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
@Aspect
public class OrderDataSourceInterceptor {

    @Autowired
    private OrderUtils orderUtils;

    @Before("@annotation(orderDataSource)")
    public void setOrderDataSource(JoinPoint point, OrderDataSource orderDataSource) {
        System.out.println("OrderDataSourceInterceptor.setOrderDataSource");

        // 如何获取到目标方法中的user对象？？？
        Object[] args = point.getArgs();

        // 2.从args中找到user对象
        User user = null;
        for (int i = 0; i < args.length; i++) {
            if (args[i] instanceof User) {
                user = (User) args[i];
                break;
            }
        }
        if (user != null) {

            // 获取用户Id后四位
            String userSufId = orderUtils.getUserSufId(user.getId().toString());

            // 根据用户id后四位%数据库的数量
            Integer dbIndex = (Integer.parseInt(userSufId) % RabbitMQConstants.ORDER_DB_SIZE) + 1;

            // 计算表的编号
            Integer tabIndex = ((Integer.parseInt(userSufId) / RabbitMQConstants.ORDER_DB_SIZE) % RabbitMQConstants.ORDER_TABLE_SIZE) + 1;

            // 把表的编号设置到ThreadLocal中
            OrderTableIndexThreadLocal.set(tabIndex);

            System.out.println("dbIndex:" + dbIndex);

            // 设置数据源
            DynamicDataSourceContextHolder.push("order-" + dbIndex);
        } else {
            throw new ShopException(1001, "操作订单user不能为空");
        }

    }
}
